package samsung.other;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import samsung.entities.Country;
import samsung.exceptions.WrongCountryInfoException;

/**
 * Class need for parsing information about country from string that was entered
 * to console.
 *
 * @author Vitaliy Muzalevskiy
 */
public class CountryInfoParser {
    
    /**
     * Method parse entered information and get name of the country from it.
     *
     * @param countryInfo - information entered to console.
     * @return <code>String</code> value of country name.
     * @throws WrongCountryInfoException if was entered wrong country information.
     */
    public static String getCountryName(String countryInfo)
            throws WrongCountryInfoException {
        String result = new String();
        Pattern pattern = Pattern.compile("[a-z|A-Z|а-я|А-Я|\\s]+[a-z|а-я](?=\\s+\\d)");
        Matcher match = pattern.matcher(countryInfo);
        match.find();
        try{
            result = match.group();
        }catch (IllegalStateException e){
            throw new WrongCountryInfoException();
        }
        if(result.length() > Country.NAME_MAX_LENGTH){
            throw new WrongCountryInfoException();
        }
        return result;
    }
    
    /**
     * Method parse entered information and get data about situation of
     * country in current area.
     *
     * @param countryInfo - information entered to console. 
     * @return <code>CountryArea</code> object that describe the position
     *      of the country in area.
     * @throws WrongCountryInfoException if was entered wrong country information.
     */
    public static CountryArea getCountryArea(String countryInfo)
            throws WrongCountryInfoException {
        List<Integer> values = new ArrayList();
        int xDownLeft;
        int yDownLeft;
        int xUpRight;
        int yUpRight;
        Pattern pattern = Pattern.compile("(?<=\\s)[\\d|.|,]+(?=\\s*)");
        Matcher match = pattern.matcher(countryInfo);
        while(match.find()){
            try {
                values.add(Integer.parseInt(match.group()));
            }catch(NumberFormatException e){
                throw new WrongCountryInfoException();
            }
        }
        if(values.size() != 4){
            throw new WrongCountryInfoException();
        }
        xDownLeft = values.get(0);
        yDownLeft = values.get(1);
        xUpRight = values.get(2);
        yUpRight = values.get(3);
        return new CountryArea(new Position(xDownLeft, yDownLeft), 
                new Position(xUpRight, yUpRight));
    }
}
